package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auth.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author houChen
 * @date 2021/12/27 21:21
 * @Description:  处理社交登录请求
 */
@Controller
public class OAuth2Contriller {

    @Autowired
    MemberFeignService memberFeignService;


    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        //根据code码，换取access_token
        Map<String, String> map = new HashMap<>();
        map.put("client_id", "2362606657");
        map.put("client_secret", "78533622143269d1728d3ae6fdbd8c67");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.gulimall.com:20001/oauth2.0/weibo/success");
        map.put("code", code);
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), null, map);

        //处理
        if(response.getStatusLine().getStatusCode()==200){
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            //知道当前是哪个社交用户
            //1、当前用户如果是第一次进网站，自动注册进来（为当前社交用户生成一个会员信息账号，以后这个社交账号对应这个会员）
            //登录或者注册这个社交用户
            R socialLogin = memberFeignService.login(socialUser);
            if(socialLogin.getCode()==0){
                MemberRespVo data = socialLogin.getData(new TypeReference<MemberRespVo>() {
                });
                //2、登录成功就跳回首页
                //第一次使用session时，服务端会命令浏览器保存一个cookie,cookie中包含一个jsessionid,
                //以后浏览器访问这个域名下的服务时，会带上这个cookie
                //1、todo 默认发的令牌 session = xxxx  作用域：当前域  =》 如何解决子域的session共享问题
                //2、todo 使用JSON的序列化，序列化对象到redis中
                session.setAttribute("loginUser", data);
                return "redirect:http://gulimall.com:10001";
            }else{
                return "redirect:http://auth.gulimall.com:20001/login.html";
            }
        }else{
            return "redirect:http://auth.gulimall.com:20001/login.html";
        }
    }
}